class RecordController {

    def index = { }
    
    def create = {
    	[activity : Activity.get(params.activity.id)]
    }
    
    def activitySelect = {
    	params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ activityList: Activity.list( params ), activityTotal: Activity.count() ]
    }
    
    def uidSave = {
    	def person = Person.findByUid(params.uid)
    	if (!person) {
    		flash.message = "查無此人"
    		redirect(action:create, params:['activity.id':params.activity.id])
    	}
    	
    	def activity = Activity.get(params.activity.id)
    	activity.records.each { re ->
    		if (re.person.uid.equals(params.uid)) {
    			flash.message = person.name + "已經存在"
    			redirect(action:create, params:['activity.id':params.activity.id])
    			return
    		}
    	}
    	
    	(new Record([person:person,activity:activity])).save()
    	flash.message = person.name + ' 成功加入應出席名單 '
    	redirect(action:create, params:['activity.id':activity.id])
    }
    
    def save = {
    	def activity = Activity.get(params.activity.id)
    	def tags
    	if (params.sport.id.toInteger() > 0) {
    		def sport = Sport.get(params.sport.id)
    		tags = SportTag.findAllBySport(sport)
    	}
    	if (params.category.id.toInteger() > 0) {
    		def category = Vcategory.get(params.category.id)
    		tags = CategoryTag.findAllByCategory(category);
    	}
    	tags.each { t ->
    		def r = Record.findByActivityAndPerson(activity, t.person)
    		if (!r) {
    			(new Record([person:t.person,activity:activity])).save()
    		}
    	}
    	redirect(action:create, params:['activity.id':activity.id])
    }
    
    def delete = {
    	def record = Record.get( params.id )
    	if (record) {
    		record.delete(flush:true)
    		redirect(action:create, params:['activity.id':params.activity.id])
    	}
    }
}
